package com.smartfast4j.api.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartfast4j.api.common.bean.IpInfo;
import com.smartfast4j.api.service.ApiService;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * API
 */
@RestController
@RequestMapping("/api")
public class ApiController extends BaseController {


    @Value("${api.url.userIp}")
    private String userIp;

    @Autowired
    private ApiService apiService;

    /**
     *
     * 1.获取客户端信息
     * @return
     */
    @RequestMapping("/userIp")
    public R userIp(){
       String retVal = HttpUtil.get(userIp);
       if(StringUtils.isNotEmpty(retVal)){
           JSONObject jsonObject = JSON.parseObject(retVal);
           if(jsonObject.getInteger("errorCode")==0){
               JSONObject dataJson = jsonObject.getJSONObject("data");
               return R.ok(dataJson);
           }
       }
       return R.ok();
    }

    /**
     * 2.根据IP地址获取信息
     * @param ip
     * @return
     */
    @RequestMapping("/ipInfo")
    public R ipInfo(@RequestParam String ip){
        IpInfo ipInfo = apiService.searchIp(ip);
        return R.ok(ipInfo);
    }

    /**
     * 3.根据IP地址查询IP信息
     * @param ip
     * @return
     */
    @RequestMapping("/searchIp")
    public IpInfo searchIp(String ip){
        IpInfo ipInfo = apiService.searchIp(ip);
        return ipInfo;
    }



    /**
     * 判断是否为正整数
     * @param input
     * @return
     */
    private boolean isInteger(String input) {
        Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(input);
        return mer.find();
    }
}
